package com.hejia.alauda.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.bson.types.ObjectId;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.LocalDate;
import org.springframework.core.env.Environment;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hejia.alauda.Constants;
import com.hejia.alauda.entity.BonusOrder;
import com.hejia.alauda.entity.BonusRecord;
import com.hejia.alauda.entity.Message;
import com.hejia.alauda.entity.Order;
import com.hejia.alauda.entity.PushMessage;
import com.hejia.alauda.entity.Redpacket;
import com.hejia.alauda.entity.User;
import com.hejia.alauda.entity.UserInformation;
import com.hejia.alauda.entity.example.BonusOrderExample;
import com.hejia.alauda.entity.example.BonusRecordExample;
import com.hejia.alauda.mongodb.IwxTicket;
import com.hejia.alauda.persistence.mybatis.BonusOrderMapper;
import com.hejia.alauda.persistence.mybatis.BonusRecordMapper;
import com.hejia.alauda.utils.DateTimeUtil;
import com.hejia.alauda.utils.Pager;
import com.hejia.alauda.utils.Utils;
import com.hejia.hermes.service.SMSService;
import com.umeng.config.UmengConfig;

import static com.hejia.alauda.event.EventConstant.*;

@Service
public class BonusServiceImpl implements BonusService {

	private static final Log logger = LogFactory.getLog(BonusServiceImpl.class);
	
	@Resource
	public MongoTemplate mongoTemplate;
	
	@Resource
	private Environment environment;
	
	@Resource
	private BonusOrderMapper bonusOrderMapper;

	@Resource
	private BonusRecordMapper bonusRecordMapper;

	@Resource
	private OrderService orderService;

	@Resource
	private RedEnvelopeService redEnvelopeService;

	@Resource
	private PaymentService paymentService;
	
	@Resource
	private PushMessageService pushMessageService;
	
	@Resource(name = "sendSMS")
	private SMSService smsService;

	@Resource
	private UserService userService;

	@Resource
	private MessageService messageService;
	
	@Resource
	private ActivityService activityService;
	
	@Resource
	private CommonService commonService;
	
	@Override
	public List<BonusRecord> findCanCashBonusesByOrderNumber(String orderNumber) {

		// 订单是否已经支付
		Order order = this.orderService.findOrderByPayNumber(orderNumber);
		if (order.getStatus() != Order.Status.STATUS_PAID) {
			return new ArrayList<>();
		}

		// 是否红包提现购买订单或红包是否已经提现
		List<BonusOrder> bonusOrders = this.findBonusOrdersByOrderId(order
				.getId());
		if (bonusOrders.size() != 1) {
			return new ArrayList<>();
		}

		BonusOrder bonusOrder = bonusOrders.get(0);
		Redpacket redpacket = redEnvelopeService.getRedpacketByCode(bonusOrder
				.getBonusRecord().getCode());

		// 获取提现红包
		BonusRecordExample example = new BonusRecordExample();
		example.appendCriterion("user_id =", bonusOrder.getBonusRecord()
				.getUser().getId());
		example.appendCriterion("code =", redpacket.getCode());
		example.appendCriterion("date(expiredDate) >= date(now())");
		example.appendCriterion("consume = 0");
		example.setOrderByClause("expiredDate");

		return this.bonusRecordMapper.selectByExample(example, null);
	}

	/**
	 * 查询订单激活的红包订单
	 * 
	 * @param orderId
	 *            订单ID
	 * @return
	 */
	public List<BonusOrder> findBonusOrdersByOrderId(Long orderId) {
		BonusOrderExample example = new BonusOrderExample();
		example.appendCriterion("order_id =", orderId);
		return this.bonusOrderMapper.selectByExample(example, null);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void cashBonus(String orderNumber, Long[] bonusRecordIds) {

		if (bonusRecordIds == null || bonusRecordIds.length < 1) {
			throw new RuntimeException("提现红包列表为空");
		}

		// 订单是否已经支付
		Order order = this.orderService.findOrderByPayNumber(orderNumber);
		if (order.getStatus() != Order.Status.STATUS_PAID) {
			throw new RuntimeException("订单未支付");
		}

		// 下单指定时间后，不允许提现
		int days = Days.daysBetween(new DateTime(order.getCreateDate()),
				new DateTime()).getDays();
		if (days > 2) {
			throw new RuntimeException("超过可提现时间");
		}

		// 是否红包提现购买订单或红包是否已经提现
		List<BonusOrder> bonusOrders = this.findBonusOrdersByOrderId(order
				.getId());
		if (bonusOrders.size() != 1) {
			throw new RuntimeException("红包已提现");
		}

		BonusOrder bonusOrder = bonusOrders.get(0);
		Redpacket redpacket = redEnvelopeService.getRedpacketByCode(bonusOrder
				.getBonusRecord().getCode());

		// 提现额度是否用完
		int amount = order.getAmount().intValue();
		amount = amount - redpacket.getWithdrawLimit();
		if (amount <= 0) {
			throw new RuntimeException("超过提现额度");
		}

		// 获取提现红包
		BonusRecordExample example = new BonusRecordExample();
		List<Long> list = new ArrayList<>();
		for (Long id : bonusRecordIds) {
			list.add(id);
		}
		example.appendCriterion("id in ", list);
		example.setOrderByClause("expiredDate");

		List<BonusRecord> bonusRecords = this.bonusRecordMapper
				.selectByExample(example, null);
		if (bonusRecords.size() < 1) {
			throw new RuntimeException("查询不到红包记录");
		}

		for (BonusRecord bonusRecord : bonusRecords) {
			if (!bonusRecord.getUser().getId()
					.equals(bonusRecord.getUser().getId())) {
				throw new RuntimeException("不能提现非本人红包");
			}

			if (!bonusRecord.getCode().equals(redpacket.getCode())) {
				throw new RuntimeException("不能提现不同类别红包");
			}

			if (bonusRecord.getConsume()) {
				throw new RuntimeException("红包已提现");
			}

			LocalDate expiredDate = new DateTime(bonusRecord.getExpiredDate())
					.toLocalDate();
			if (expiredDate.compareTo(new LocalDate()) < 0) {
				throw new RuntimeException("红包已过期");
			}

			amount = amount - redpacket.getWithdrawLimit();
			if (amount < 0) {
				throw new RuntimeException("超过提现额度");
			}

			cashBonus(order, bonusRecord);
		}
	}

	/**
	 * 提现红包
	 * 
	 * @param order
	 *            订单
	 * @param bonusRecord
	 *            红包
	 */
	private void cashBonus(Order order, BonusRecord bonusRecord) {

		// 检查是否用户自己红包
		if (order.getUser().getId() != bonusRecord.getUser().getId()) {
			throw new RuntimeException("不是本人红包");
		}

		// 是否已过期
		if (bonusRecord.getExpiredDate().before(new Date())) {
			throw new RuntimeException("红包已过期");
		}

		// 判断该红包是否已激活
		BonusOrderExample example = new BonusOrderExample();
		example.appendCriterion("bonusRecord_id=", bonusRecord.getId());
		if (bonusOrderMapper.countByExample(example) > 0) {
			throw new RuntimeException("红包不能重复提现");
		}

		// 激活红包
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", bonusRecord.getId());
		params.put("consume", Boolean.TRUE);
		params.put("consumeDate", new Date());
		params.put("remaining", 0);
		if (bonusRecordMapper.updateConsumeById(params) < 1) {
			throw new RuntimeException("提现红包失败");
		}

		BonusOrder bonusOrder = new BonusOrder();
		bonusOrder.setCreateDate(new Date());
		bonusOrder.setModifyDate(new Date());
		bonusOrder.setAmount(bonusRecord.getAmount());
		bonusOrder.setBonusRecord(bonusRecord);
		bonusOrder.setOrder(order);
		bonusOrder.setRepaid(Boolean.FALSE);
		if (bonusOrderMapper.insert(bonusOrder) < 1) {
			throw new RuntimeException("提现红包失败");
		}

		// 申请打款
		paymentService.applyBonusRepay(bonusOrder.getId());
	}

	@Override
	public Map<String, Object> countCanCashBonusesByBonusRecordId(
			Long bonusRecordId) {
		BonusRecord bonusRecord = this.bonusRecordMapper
				.selectByPrimaryKey(bonusRecordId);
		return this.bonusOrderMapper.countCanCashBonusesByCode(bonusRecord
				.getUser().getId(), bonusRecord.getCode());
	}

	@Override
	public BonusRecord findBonusRecordById(Long bonusRecordId) {
		return this.bonusRecordMapper.selectByPrimaryKey(bonusRecordId);
	}

	@Override
	public boolean enableContinueCashBunus(Long orderId) {

		// 订单是否已经支付
		Order order = this.orderService.findOrderById(orderId);
		if (order.getStatus() != Order.Status.STATUS_PAID) {
			return false;
		}

		// 是否红包提现购买订单或红包是否已经提现
		List<BonusOrder> bonusOrders = this.findBonusOrdersByOrderId(order
				.getId());
		if (bonusOrders.size() != 1) {
			return false;
		}

		return true;
	}

	@Override
	public Integer getEnableCashBonusCount(Long orderId) {

		// 订单是否已经支付
		Order order = this.orderService.findOrderById(orderId);
		if (order.getStatus() != Order.Status.STATUS_PAID) {
			return 0;
		}

		// 是否红包提现购买订单或红包是否已经提现
		List<BonusOrder> bonusOrders = this.findBonusOrdersByOrderId(order
				.getId());
		if (bonusOrders.size() != 1) {
			return 0;
		}

		BonusOrder bonusOrder = bonusOrders.get(0);
		Redpacket redpacket = redEnvelopeService.getRedpacketByCode(bonusOrder
				.getBonusRecord().getCode());

		// 提现额度是否用完
		int amount = order.getAmount().intValue();
		amount = amount - redpacket.getWithdrawLimit();
		if (amount <= 0) {
			return 0;
		}

		// 获取提现红包
		BonusRecordExample example = new BonusRecordExample();
		example.appendCriterion("user_id =", bonusOrder.getBonusRecord()
				.getUser().getId());
		example.appendCriterion("code =", redpacket.getCode());
		example.appendCriterion("date(expiredDate) >= date(now())");
		example.appendCriterion("consume = 0");
		example.setOrderByClause("expiredDate");

		// 可提现红包数
		int count = 0;
		List<BonusRecord> bonusRecords = this.bonusRecordMapper
				.selectByExample(example, null);
		for (BonusRecord bonusRecord : bonusRecords) {
			amount = amount - redpacket.getWithdrawLimit();
			if (amount >= 0) {
				count++;
			}
		}

		return count;
	}

	@Override
	public BonusRecord findOrderFirstBonus(Long orderId) {
		BonusOrderExample example = new BonusOrderExample();
		example.appendCriterion("order_id =", orderId);
		example.setOrderByClause("id");
		Pager<BonusOrder> pager = new Pager<>();
		pager.setPageSize(1);
		List<BonusOrder> bonusOrders = this.bonusOrderMapper.selectByExample(
				example, pager);
		if (bonusOrders.size() > 0) {
			return bonusOrders.get(0).getBonusRecord();
		}
		return null;
	}

	@Override
	public Pager<BonusRecord> findBonusRecords(Pager<BonusRecord> pager,
			String keyword, Boolean consume) {
		if (StringUtils.isEmpty(keyword)) {
			keyword = "%";
		} else {
			keyword = "%" + keyword + "%";
		}
		pager.setList(this.bonusRecordMapper.findBonusRecords(pager, keyword,
				consume));
		pager.setTotalCount(this.bonusRecordMapper.countBonusRecords(keyword,
				consume));
		return pager;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void cashBonus(Long bonusRecordId, Long orderId) {
		BonusRecord bonusRecord = this.bonusRecordMapper
				.selectByPrimaryKey(bonusRecordId);
		Order order = this.orderService.findOrderById(orderId);
		
		BonusOrderExample bonusOrderExample = new BonusOrderExample();
		bonusOrderExample.appendCriterion("order_id =", orderId);
		List<BonusOrder> bonusOrders = this.bonusOrderMapper.selectByExample(bonusOrderExample, null);
		
		// 订单提现红包金额
		Integer amount = bonusRecord.getRedpacket().getWithdrawLimit();
		if (bonusOrders.size() > 0) {
			for (BonusOrder bonusOrder : bonusOrders) {
				amount += bonusOrder.getBonusRecord().getRedpacket().getWithdrawLimit();
			}
		}
		
		if (BigDecimal.valueOf(amount).compareTo(order.getAmount()) <= 0) {
			this.cashBonus(order, bonusRecord);
		} else {
			throw new RuntimeException("超过订单可提现红包");
		}
	}

	@Override
	public BonusRecord addBonusRecordByRedpacket(User user, String code, BigDecimal amount) {
		Redpacket red = redEnvelopeService.getRedpacketByCode(code);
		BonusRecord record = new BonusRecord();
		if (amount == null) {
			record.setAmount(new BigDecimal(red.getValue()));
		} else {
			record.setAmount(amount);
		}
		record.setDescription(red.getIntroduction());
		record.setType(code);
		record.setCode(code);
		record.setConsume(false);
		record.setUser(user);
		record.setRemaining(record.getAmount());
		record.setCreateDate(Calendar.getInstance().getTime());
		record.setModifyDate(record.getCreateDate());
		if (red.getAvailableTime() == null) {
			record.setExpiredDate(DateTimeUtil.getDateDay(red.getInvalidDate()));
		} else {
			record.setExpiredDate(DateUtils.addDays(record.getCreateDate(), red.getAvailableTime() - 1));
		}
		
		this.bonusRecordMapper.insert(record);
		
		return record;
	}

	@Override
	public List<Long> findOneDayExpirePushAlertBonusRecordIds() {
		return this.bonusRecordMapper.findOneDayExpirePushAlertBonusRecordIds();
	}

	@Override
	public void sendOneDayExpirePushAlert(UmengConfig umengConfig, Long bonusRecordId) throws Exception {
		
		BonusRecord bonusRecord = this.bonusRecordMapper.selectByPrimaryKey(bonusRecordId);
		
		LocalDate now = new LocalDate();
		LocalDate expiredDate = new LocalDate(bonusRecord.getExpiredDate());
		if (now.isAfter(expiredDate)) {
			return;
		}
		if (bonusRecord.getConsume()) {
			return;
		}
		if (bonusRecord.getOneDayExpirePushAlerted() != null 
		&& bonusRecord.getOneDayExpirePushAlerted()) {
			return;
		}
		
		Redpacket redpacket = this.redEnvelopeService.getRedpacketByCode(bonusRecord.getCode());
		String message = String.format("%s【面额%s元】马上过期啦，立即去提现", 
				redpacket.getName(), bonusRecord.getAmount());
		
		PushMessage pushMessage = new PushMessage();
		pushMessage.setUser(bonusRecord.getUser());
		pushMessage.setOpenAppPage(PushMessage.OPEN_APP_PAGE_MY_BONUS);
		pushMessage.setAlert(message + "~ >>>");
		
		if (pushMessage.getUser() == null) {
			throw new RuntimeException("推送用户不能为空");
		}
		
		if (environment.acceptsProfiles(Constants.PROFILE_PRODUCTION)) {
			pushMessage.setProductionMode(PushMessage.PRODUCTION_MODE_TRUE);
		} else {
			pushMessage.setProductionMode(PushMessage.PRODUCTION_MODE_FALSE);
		}
		
		// 发送App消息
		this.messageService.sendAppMessage(
				bonusRecord.getUser(), Message.CATEGORY_BONUS, message,  null);
				
		// 无法判断用户属于哪个平台，都发送
		boolean iOSPush = this.pushMessageService.pushIOSMessage(umengConfig, pushMessage);
		boolean androidPush = this.pushMessageService.pushAndroidMessage(umengConfig, pushMessage);
		if (!iOSPush && !androidPush) {
			return;
		}
		
		bonusRecord.setOneDayExpirePushAlerted(true);
		if (this.bonusRecordMapper.updateOneDayExpirePushAlertById(bonusRecord.getId()) < 1) {
			throw new RuntimeException("更新红包失败");
		}
	}

	@Override
	public List<Long> findOneDayExpireSmsAlertBonusRecordIds() {
		return this.bonusRecordMapper.findOneDayExpireSmsAlertBonusRecordIds();
	}

	@Override
	public void sendOneDayExpireSmsAlert(Long bonusRecordId) {
		
		BonusRecord bonusRecord = this.bonusRecordMapper.selectByPrimaryKey(bonusRecordId);
		
		LocalDate now = new LocalDate();
		LocalDate expiredDate = new LocalDate(bonusRecord.getExpiredDate());
		if (now.isAfter(expiredDate)) {
			return;
		}
		if (bonusRecord.getConsume()) {
			return;
		}
		if (bonusRecord.getOneDayExpireSmsAlerted() != null 
		&& bonusRecord.getOneDayExpireSmsAlerted()) {
			return;
		}
		
		Redpacket redpacket = this.redEnvelopeService.getRedpacketByCode(bonusRecord.getCode());
		String message = String.format("%s【面额%s元】马上过期啦，立即去提现！", 
				redpacket.getName(), bonusRecord.getAmount());
		
		// 发送App消息
		this.messageService.sendAppMessage(
				bonusRecord.getUser(), Message.CATEGORY_BONUS, message,  null);
		
		// 发送短信
		if (environment.acceptsProfiles(Constants.PROFILE_PRODUCTION)) {
			this.userService.sendUniversalMessage(
					bonusRecord.getUser().getMobile(), message, "alauda_activity");
		} else {
			logger.info("发送短信:" + message);
		}
		
		bonusRecord.setOneDayExpireSmsAlerted(true);
		if (this.bonusRecordMapper.updateOneDayExpireSmsAlertById(bonusRecord.getId()) < 1) {
			throw new RuntimeException("更新红包失败");
		}
	}
	
	@Override
	public List<Long> findSevenDayExpirePushAlertBonusRecordIds() {
		return this.bonusRecordMapper.findSevenDayExpirePushAlertBonusRecordIds();
	}

	@Override
	public void sendSevenDayExpirePushAlert(UmengConfig umengConfig, Long bonusRecordId) throws Exception {

		BonusRecord bonusRecord = this.bonusRecordMapper.selectByPrimaryKey(bonusRecordId);
		
		LocalDate now = new LocalDate();
		LocalDate expiredDate = new LocalDate(bonusRecord.getExpiredDate());
		if (now.isAfter(expiredDate)) {
			return;
		}
		if (bonusRecord.getConsume()) {
			return;
		}
		if (bonusRecord.getSevenDayExpirePushAlerted() != null 
		&& bonusRecord.getSevenDayExpirePushAlerted()) {
			return;
		}
		
		Redpacket redpacket = this.redEnvelopeService.getRedpacketByCode(bonusRecord.getCode());
		String message = String.format("%s【面额%s元】7天后过期啦，立即去提现", 
				redpacket.getName(), bonusRecord.getAmount());
		
		PushMessage pushMessage = new PushMessage();
		pushMessage.setUser(bonusRecord.getUser());
		pushMessage.setOpenAppPage(PushMessage.OPEN_APP_PAGE_MY_BONUS);
		pushMessage.setAlert(message + "~ >>>");
		
		if (pushMessage.getUser() == null) {
			throw new RuntimeException("推送用户不能为空");
		}
		
		if (environment.acceptsProfiles(Constants.PROFILE_PRODUCTION)) {
			pushMessage.setProductionMode(PushMessage.PRODUCTION_MODE_TRUE);
		} else {
			pushMessage.setProductionMode(PushMessage.PRODUCTION_MODE_FALSE);
		}
		
		// 发送App消息
		this.messageService.sendAppMessage(
				bonusRecord.getUser(), Message.CATEGORY_BONUS, message,  null);
		
		// 发送推送消息，无法判断用户属于哪个平台，都发送
		boolean iOSPush = this.pushMessageService.pushIOSMessage(umengConfig, pushMessage);
		boolean androidPush = this.pushMessageService.pushAndroidMessage(umengConfig, pushMessage);
		if (!iOSPush && !androidPush) {
			return;
		}
		
		bonusRecord.setSevenDayExpirePushAlerted(true);
		if (this.bonusRecordMapper.updateSevenDayExpirePushAlertById(bonusRecord.getId()) < 1) {
			throw new RuntimeException("更新红包失败");
		}
	}

	@Override
	public boolean isSendedBirthdayBonus(Long userId, Date birthday) {
		
		BonusRecordExample example = new BonusRecordExample();
		example.appendCriterion("date(createDate) = ", birthday);
		example.appendCriterion("user_id = ", userId);
		example.appendCriterion("code =", Redpacket.CODE_BIRTHDAY);
		
		return this.bonusRecordMapper.countByExample(example) > 0;
	}

	@Override
	public void sendBirthdayBonus(Long userId, Date birthday) {
		
		// 检查是否用户生日
		User user = this.userService.findUserById(userId);
		if (user == null 
		|| StringUtils.isEmpty(user.getIdCard())
		|| user.getIdCard().length() != 18
		|| !user.getIdCard().substring(10, 14).equals(DateFormatUtils.format(birthday, "MMdd"))) {
			return;
		}
		
		// 检查是否已发送红包
		if (this.isSendedBirthdayBonus(user.getId(), new LocalDate(birthday).toDate())) {
			return;
		}
		
		// 发送红包
		this.addBonusRecordByRedpacket(user, Redpacket.CODE_BIRTHDAY, BigDecimal.valueOf(20));
		Redpacket redpacket = this.redEnvelopeService.getRedpacketByCode(Redpacket.CODE_BIRTHDAY);
		String message = String.format("衷心的祝您生日快乐，在此奉上%s元红包聊表心意，请至我的红包提现", redpacket.getValue());
		
		// 发送红包消息
		this.userService.sendUniversalMessage(user.getMobile(), message, "alauda_notify");
		this.messageService.sendAppMessage(user, Message.CATEGORY_BONUS, message, null);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, timeout = 3000)
	public void insertBonusRecord(BonusRecord bonusRecord) {
		this.bonusRecordMapper.insert(bonusRecord);
	}

	@Override
	public boolean generateBonusTicket() {
		JSONObject config = activityService.getActivityConfig("2015_HEJIA_ONEYEAR_ACTIVITY_CONFIG").getJSONObject("sales-bonus-config");
		String starting_date = config.getString("starting-date"),expiring_date=config.getString("expiring-date");
		Calendar calendar = Calendar.getInstance();
		String now = Utils.formatDate(calendar);
		if(now.compareTo(starting_date)>=0 && now.compareTo(expiring_date)<=0){
			int hour = calendar.get(Calendar.HOUR_OF_DAY);
			if(config.getJSONArray("times").contains(hour)){
				commonService.setMongodbForValue(MONGODB_KEY_BUY_NOW_CURRENT_STEP, now + "-" + hour);
				return true;
			}
		}
		return false;
//		long now = System.currentTimeMillis(),starting_date = config.getLongValue("starting-date"),expiring_date=config.getLongValue("expiring-date");
//		if (starting_date <= now && now <= expiring_date) {
//			int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
//			if(config.getJSONArray("times").contains(hour)){
//				List<IwxTicket> list = mongoTemplate.find(new Query(new Criteria("type").is("BuyNow")), IwxTicket.class);
//				if(list!=null){
//					for(IwxTicket item : list){
//						mongoTemplate.remove(item);
//					}
//				}
//				JSONArray bonus = config.getJSONArray("bonus");
//				for(int i=0;i<bonus.size();i++){
//					JSONObject item = bonus.getJSONObject(i);
//					int rate = item.getIntValue("rate");
//					for(int j=0;j<rate;j++){
//						IwxTicket ticket = new IwxTicket();
//						ticket.setId(new ObjectId());
//						ticket.setValue(item.getIntValue("amount"));
//						ticket.setCode(ticket.getId().toHexString());
//						ticket.setType("BuyNow");
//						ticket.setCreateDate(Utils.formatDateTime(new Date()));
//						ticket.setModifyDate(ticket.getCreateDate());
//						logger.info("============>" + ticket);
//						mongoTemplate.save(ticket);
//					}
//				}
//			}
//		}
	}

	@Override
	public List findBonusTicket(String key, JSONObject config) {
		List pool = new ArrayList();
		JSONArray bonus = config.getJSONArray("bonus");
		for(int i=0;i<bonus.size();i++){
			JSONObject item = bonus.getJSONObject(i);
			int rate = item.getIntValue("rate");
			
			for(int j=0;j<rate;j++){
				pool.add(item);
			}
//			BonusRecordExample example = new BonusRecordExample();
//			example.appendCriterion("amount=", item.getIntValue("amount"));
//			example.appendCriterion("`type` LIKE \'%"+config.getString("key_word")+"%\'");
//			example.appendCriterion("related=", key);
//			int count = bonusRecordMapper.countByExample(example);
//			int remains = rate - count;
//			if(remains>0){
//				for(int j=0;j<remains;j++){
//					pool.add(item);
//				}
//			}
		}
		return pool;
	}

	@Override
	public void updateIwxTicket(IwxTicket iwxTicket) {
		mongoTemplate.save(iwxTicket);
	}
	
	@Override
	public Integer countUnusedBonusRecordByUser(User user){
		BonusRecordExample example = new BonusRecordExample();
		example.appendCriterion("user_id=", user.getId());
		example.appendCriterion("consume=", false);
		example.appendCriterion("expiredDate > ", new Date());
		return bonusRecordMapper.countByExample(example);
	}

	
}
